import 'package:factoryside/api/api.dart';
import 'package:factoryside/bean/addr_entity.dart';
import 'package:factoryside/bean/area_list_entity.dart';
import 'package:factoryside/bean/city_list_entity.dart';
import 'package:factoryside/bean/district_list_entity.dart';
import 'package:factoryside/bean/province_list_entity.dart';
import 'package:factoryside/service/order_service.dart';
import 'package:factoryside/utils/ColorsUtils.dart';
import 'package:factoryside/utils/request_util.dart';
import 'package:factoryside/utils/utils.dart';
import 'package:factoryside/widget/jh_login_textfield.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

///收货地址页面

class AddressPage extends StatefulWidget {
  AddrData addr;

  AddressPage(this.addr);

  @override
  State<StatefulWidget> createState() {
    return _AddressState();
  }
}

class _AddressState extends State<AddressPage> {
  List values = List();
  AddrData addr;
  ProvinceListData province;
  CityListDataData city;
  AreaListDataData area;
  DistrictListDataData district;
  String provinceName;
  String cityName;
  String areaName;
  String districtName;
  String detail;
  TextEditingController nameCtr = TextEditingController();
  TextEditingController phoneCtr = TextEditingController();
  TextEditingController addrCtr = TextEditingController();
  TextEditingController detailCtr = TextEditingController();

  bool isDefault = false;
  @override
  void dispose() {
    super.dispose();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (widget.addr != null) {
      addr = widget.addr;
      provinceName = addr.province;
      cityName = addr.city;
      areaName = addr.area;
      districtName = addr.district;
      addrCtr.text = '$provinceName$cityName$areaName$districtName';
      detail = addr.address;
      nameCtr.text = addr.userName;
      phoneCtr.text = addr.phone;
      detailCtr.text = addr.address;
      isDefault = addr.isDefault == '1';
    }
    setState(() {});
  }

  /// 弹出底部菜单列表模态对话框
  Future<int> _showModalBottomSheet() {
    var height = MediaQuery.of(context).size.height;
    return showModalBottomSheet<int>(
      context: context,
      builder: (context) {
        return StatefulBuilder(builder: (context, state) {
          return Container(
            margin: EdgeInsets.all(10),
            height: height / 3 * 2,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Padding(
                    padding: EdgeInsets.all(10),
                    child: Text(
                      '请选择所在地区',
                      textAlign: TextAlign.center,
                    )),
                Divider(
                  height: 1,
                ),
                GestureDetector(
                    onTap: () {
                      state(() {
                        OrderService.getProvince().then((value) {
                          state(() {
                            values = value.data;
                          });
                        });
                      });
                    },
                    child: Padding(
                        padding: EdgeInsets.all(10),
                        child: Text(
                          province != null ? province.name : '请选择省',
                          style: TextStyle(color: Colors.grey),
                        ))),
                Visibility(
                    visible: province != null,
                    child: GestureDetector(
                      onTap: () {
                        state(() {
                          OrderService.getCity(province.code).then((value) {
                            state(() {
                              values = value.data.data;
                            });
                          });
                        });
                      },
                      child: Padding(
                          padding: EdgeInsets.all(10),
                          child: Text(
                            city != null ? city.name : '请选择市',
                            style: TextStyle(color: Colors.grey),
                          )),
                    )),
                Visibility(
                    visible: city != null,
                    child: GestureDetector(
                      onTap: () {
                        state(() {
                          OrderService.getArea(city.code).then((value) {
                            state(() {
                              values = value.data.data;
                            });
                          });
                        });
                      },
                      child: Padding(
                          padding: EdgeInsets.all(10),
                          child: Text(
                            area != null ? area.name : '请选择区',
                            style: TextStyle(color: Colors.grey),
                          )),
                    )),
                Visibility(
                    visible: area != null,
                    child: GestureDetector(
                      onTap: () {
                        state(() {
                          OrderService.getDistrict(area.code).then((value) {
                            state(() {
                              values = value.data.data;
                            });
                          });
                        });
                      },
                      child: Padding(
                          padding: EdgeInsets.all(10),
                          child: Text(
                            district != null ? district.name : '请选择街道',
                            style: TextStyle(color: Colors.grey),
                          )),
                    )),
                Divider(),
                Expanded(
                  child: ListView(
                    shrinkWrap: true,
                    children: values
                        .map((e) => GestureDetector(
                              onTap: () {
                                state(() {
                                  if (e is ProvinceListData) {
                                    province = e;
                                    provinceName = e.name;
                                    OrderService.getCity(province.code)
                                        .then((value) {
                                      state(() {
                                        values = value.data.data;
                                      });
                                    });
                                  } else if (e is CityListDataData) {
                                    city = e;
                                    cityName = e.name;
                                    OrderService.getArea(city.code)
                                        .then((value) {
                                      state(() {
                                        values = value.data.data;
                                      });
                                    });
                                  } else if (e is AreaListDataData) {
                                    area = e;
                                    areaName = e.name;
                                    OrderService.getDistrict(area.code)
                                        .then((value) {
                                      state(() {
                                        values = value.data.data;
                                      });
                                    });
                                  } else if (e is DistrictListDataData) {
                                    district = e;
                                    districtName = e.name;
                                    Navigator.of(context).pop();
                                    setState(() {
                                      addrCtr.text =
                                          '$provinceName$cityName$areaName$districtName';
                                    });
                                  }
                                });
                              },
                              child: Padding(
                                padding: EdgeInsets.all(10),
                                child: Text(e.name),
                              ),
                            ))
                        .toList(),
                  ),
                )
              ],
            ),
          );
        });
      },
      elevation: 10,
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(10), topRight: Radius.circular(10))),
    );
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar:
          buildAppBar(widget.addr != null ? '编辑收件地址' : '添加收件地址', null, context),
      body: Column(
        children: [
          Expanded(
            child: ListView(
              children: [
                Container(
                    color: Colors.white,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        Container(
                          padding: EdgeInsets.all(10),
                          child: Row(
                            children: [
                              Expanded(
                                child: JhLoginTextField(
                                  controller: nameCtr,
                                  text: addr == null ? '' : addr.userName,
                                  hintText: '收件人姓名',
                                  border: InputBorder.none,
                                  isShowDeleteBtn: true,
                                  isDense: true,
                                ),
                              )
                            ],
                          ),
                        ),
                        Divider(height: 1),
                        Container(
                          padding: EdgeInsets.all(10),
                          child: Row(
                            children: [
                              Expanded(
                                child: JhLoginTextField(
                                  controller: phoneCtr,
                                  text: addr == null ? '' : addr.phone,
                                  hintText: '手机号码',
                                  border: InputBorder.none,
                                  isShowDeleteBtn: true,
                                  isDense: true,
                                ),
                              )
                            ],
                          ),
                        ),
                        Divider(height: 1),
                        GestureDetector(
                          child: Container(
                            padding: EdgeInsets.all(10),
                            child: Row(
                              children: [
                                Expanded(
                                    child: JhLoginTextField(
                                  controller: addrCtr,
//                                  text: districtName != null
//                                      ? '$provinceName$cityName$areaName$districtName'
//                                      : '',
                                  hintText: '所在地区',
                                  border: InputBorder.none,
                                  isShowDeleteBtn: false,
                                  isDense: true,
                                  enable: false,
                                )),
                                Icon(
                                  Icons.chevron_right,
                                  color: Colors.grey,
                                )
                              ],
                            ),
                          ),
                          onTap: () {
                            OrderService.getProvince().then((value) {
                              setState(() {
                                values = value.data;
                                _showModalBottomSheet();
                              });
                            });
                          },
                        ),
                        Divider(height: 1),
                        Container(
                          padding: EdgeInsets.all(10),
                          child: Row(
                            children: [
                              Expanded(
                                child: JhLoginTextField(
                                  controller: detailCtr,
                                  text: addr == null ? '' : addr.address,
                                  hintText: '详细地址：如道路、门牌号、小区、楼栋号、单元室等',
                                  border: InputBorder.none,
                                  isShowDeleteBtn: true,
                                  isDense: true,
                                ),
                              )
                            ],
                          ),
                        ),
                        Divider(height: 1),
                      ],
                    )),
                Container(
                  color: Colors.white,
                  padding: EdgeInsets.all(10),
                  child: Row(
                    children: [
                      Expanded(child: Text('设置默认地址')),
                      Switch(
                        value: this.isDefault,
                        activeColor: Colors.blue,
                        onChanged: (value) {
                          setState(() {
                            this.isDefault = value;
                          });
                        },
                      ),
                    ],
                  ),
                ),
                Container(
                  color: Colors.transparent,
                  width: double.infinity,
                  height: 50,
                  margin: EdgeInsets.all(20),
                  child: RaisedButton(
                    onPressed: () {
                      if (isNullOrEmpty(nameCtr.text)) {
                        showToast('请输入收件人姓名');
                        return;
                      }
                      if (isNullOrEmpty(phoneCtr.text)) {
                        showToast('请输入收件人手机号');
                        return;
                      }
                      if (!RegexUtil.isMobileExact(phoneCtr.text)) {
                        showToast('请输入正确的手机号');
                        return;
                      }
                      if (isNullOrEmpty(provinceName)) {
                        showToast('请选择省市区');
                        return;
                      }
                      if (isNullOrEmpty(detailCtr.text)) {
                        showToast('请输入详细地址');
                        return;
                      }
                      if (addr == null) {
                        RequestUtil.post(Api.addAccountAddress, {
                          'UserID': Api.userName,
                          'Province': provinceName,
                          'City': cityName,
                          'Area': areaName,
                          'District': districtName,
                          'Address': detailCtr.text,
                          'IsDefault': isDefault ? '1' : '0',
                          'UserName': nameCtr.text,
                          'Phone': phoneCtr.text
                        }).then((value) => this.setState(() {
                              if (value['Data']['Item1']) {
                                Navigator.pop(context, true);
                              } else {
                                showToast(value['Data']['Item2']);
                              }
                            }));
                      } else {
                        RequestUtil.post(Api.updateAccountAddress, {
                          'AccountAdressID': addr.accountAdressID,
                          'UserID': Api.userName,
                          'Province': provinceName,
                          'City': cityName,
                          'Area': areaName,
                          'District': districtName,
                          'Address': detailCtr.text,
                          'IsDefault': isDefault ? '1' : '0',
                          'UserName': nameCtr.text,
                          'Phone': phoneCtr.text
                        }).then((value) => this.setState(() {
                              if (value['Data']['Item1']) {
                                Navigator.pop(context, true);
                              } else {
                                showToast(value['Data']['Item2']);
                              }
                            }));
                      }
                    },
                    child: Text(
                      '保存',
                      style: TextStyle(color: Colors.white),
                    ),
                    color: ColorsUtil.hexToColor(Api.btnColor),
                  ),
                ),
                Visibility(
                  visible: widget.addr != null,
                  child: Container(
                    color: Colors.transparent,
                    width: double.infinity,
                    height: 50,
                    margin: EdgeInsets.symmetric(horizontal: 20),
                    child: RaisedButton(
                      onPressed: () {
                        showDialog<Null>(
                          context: context,
                          barrierDismissible: false,
                          builder: (context) {
                            return StatefulBuilder(builder: (context, state) {
                              return AlertDialog(
                                title: Center(
                                  child: Text('是否确认删除？'),
                                ),
                                titleTextStyle: TextStyle(fontSize: 16,color: Colors.black),
                                actions: <Widget>[
                                  FlatButton(
                                    child: Text('取消'),
                                    onPressed: () {
                                      Navigator.of(context).pop();
                                    },
                                  ),
                                  FlatButton(
                                    child: Text('确定'),
                                    onPressed: () {
                                      RequestUtil.post(
                                          Api.deleteAccountAddress, {
                                        'AccountAdressID': addr.accountAdressID
                                      }).then((value) {
                                        if (value['Data']['Item1']) {
                                          Navigator.of(context).pop();
                                          Navigator.pop(this.context, true);
                                        } else {
                                          showToast(value['Data']['Item2']);
                                          Navigator.of(context).pop();
                                        }
                                      });
                                    },
                                  ),
                                ],
                              );
                            });
                          },
                        );
                      },
                      child: Text(
                        '删除',
                        style: TextStyle(color: Colors.white),
                      ),
                      color: ColorsUtil.hexToColor('#FF5858'),
                    ),
                  ),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }
}
